

<template>
  <!-- 搜索框和字段选择 -->
    <div class="search-bar">
      <el-input v-model="searchCriteria.Username" placeholder="搜索用户名" class="search-input" @input="filterTableData">
      </el-input>
      <el-input v-model="searchCriteria.Password" placeholder="搜索密码" class="search-input" @input="filterTableData">
      </el-input>
      <el-input v-model="searchCriteria.Ad_user_id" placeholder="搜索AD用户" class="search-input" @input="filterTableData">
      </el-input>
      <el-button @click="filterTableData">搜索</el-button>
    </div>
  <div class="search-bar">
      <el-select v-model="searchField" placeholder="选择字段">
        <el-option label="用户名" value="Username"></el-option>
        <el-option label="密码" value="Password"></el-option>
        <el-option label="AD用户名" value="Ad_user_id"></el-option>
      </el-select>
      <el-input v-model="searchText" placeholder="请输入搜索内容" class="search-input" @input="filterTableData">
        <template #append>
          <el-button @click="filterTableData">搜索</el-button>
        </template>
      </el-input>
  </div>
  <el-dialog v-model="dialogFormVisible" v-if="dialogFormVisible" title="添加用户" width="58%">
    <Add :departmentdata="departmentdata" :userForm="userForm" @addSubmit="handleSubmit"></Add>
  </el-dialog>
  <div class="table-actions">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-button type="warning" @click="handleEdit">修改</el-button>
    <el-button type="danger" @click="handleDelete">删除</el-button>
    <el-button @click="resetDateFilter">重置日期筛选</el-button>
    <el-button @click="clearFilter">重置筛选</el-button>
  </div>
  <el-table ref="tableRef" v-loading="loading" element-loading-text="数据加载中..." row-key="date" border :data="tableData" style="width: 100%" highlight-current-row=true >
    <el-table-column prop="id" label="id" width="50"/>
    <el-table-column prop="username" label="用户名" width="80"/>
    <el-table-column prop="personname" label="姓名" min-width="80"/>
    <el-table-column prop="password" label="密码" show-overflow-tooltip width="120"/>
    <el-table-column prop="ad_user_id" label="AD账号" width="180" />
    <el-table-column prop="wechat_user_id" label="企微账号" width="180" />
    <el-table-column prop="department_id" label="部门ID" />
    <el-table-column prop="eamil" label="邮箱" width="180" />
    <el-table-column prop="phone" label="电话" width="180" />
    <el-table-column prop="create_time" label="创建时间" />
    <el-table-column prop="update_time" label="更新时间" width="180" />
    <el-table-column prop="delete_time" label="删除时间" width="180" />
    <el-table-column prop="status" label="用户状态" />
    <el-table-column prop="department_name" label="部门名称" />
    <el-table-column prop="roles_name" label="角色名称" />
    <el-table-column label="操作" fixed="right" width="180">
      <template #default="scope"> <!-- 通过插槽的scope 来绑定行数据 scope.row可以获取到当前行的数据 --->
        <el-button type="primary" size="mini" @click="handleEditRow(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini"  @click="deleteUser(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


</template>
<script lang="ts" setup>
import { ref,reactive,onMounted,toRefs } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsersAllList,delUserHandler,addUserHandler } from "../../api/user.js"
import {getDepartmentList} from "../../api/department.js"
import Add from "./Add.vue"
const tableData = ref([])
const loading = ref(true)
const dialogFormVisible = ref(false)
const searchCriteria = reactive({
        username: '',
        password: '',
        ad_user_id: ''
      })
const userForm = reactive({
    personname: "",
    username: "",
    password: "",
    checkpass: "",
    department_name: "",
    roles_name: "",
    phone: "",
    email: "",
    ad_user_id: "",
    wechat_user_id: "",
})
const filteredData = ref([])
const departmentdata= ref([])
const disabledUserId = ref("1")
const filterTableData=()=>{
  filteredData.value = tableData.value.filter(item => {
    return (
      (!searchCriteria.username || item.Username.includes(searchCriteria.username)) &&
      (!searchCriteria.password || item.Password.includes(searchCriteria.password)) &&
      (!searchCriteria.ad_user_id || item.Ad_user_id.includes(searchCriteria.ad_user_id))
    )
  })
}
// 添加用户 
const handleAdd = () =>{
  
  //addUserHandler(data).then((response)=>{
  //    console.log("response=========:",response.data)
  //})
  //const data=await getDepartmentData()
  //console.log("data++++++++++++++++++++++++++++",data)
  //departmentdata.value=data
  dialogFormVisible.value=true
  //console.log("department-------------------------",departmentdata.value)

}
// 删除用户
const deleteUser = (row) => {
  console.log("当前行的数据： ",row)
  ElMessageBox.confirm(
    row.username + '用户将被删除. 是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    loading.value=true
    delUserHandler(row.id).then((response)=>{
      console.log("response=========:",response.data)
      
      ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      getUserInfo()
    }).catch((err)=>{
      console.log(err)
    })
    
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: 'Delete canceled',
    })
  })
}
// 获取用户
const getUserInfo=()=>{
  getUsersAllList().then((response)=>{
      const result= response.data.data
      if (result){
        const base64String = result.userlist
        const decodedBytes = atob(base64String);
        // 将字节串转换为 Uint8Array
        const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
        // 使用 TextDecoder 解码为字符串
        const decoder = new TextDecoder("utf-8");
        const decodedString = decoder.decode(uint8Array);
        console.log("userinfo",decodedString)
        // window.localStorage.setItem("menus",decodedString)
        // const md5Hash = md5(decodedString+'menus_list');
        // window.localStorage.setItem("md5Hash",md5Hash)

        // 存储菜单数据到 localStorage
        // const decodedString = window.localStorage.getItem('menus');
        tableData.value = JSON.parse(decodedString)
        if (filteredData.value.length==0) {
          filteredData.value = tableData.value
        } else {
          filterTableData()
        }
        loading.value=false
        // 返回解析后的菜单数据
        //return JSON.parse(decodedString);
      }
  }).catch((err)=>{
      console.log(err)
  })
}
// 获取部门数据
  const getDepartmentData=()=>{
      getDepartmentList().then((response)=>{
        const result = response.data.data
        if (result.queryData == '[]') {
                return [];
        } else {
            const base64String = result.queryData
            const decodedBytes = atob(base64String);
            // 将字节串转换为 Uint8Array
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
            // 使用 TextDecoder 解码为字符串
            const decoder = new TextDecoder("utf-8");
            const decodedString = decoder.decode(uint8Array);
            console.log("departmentinfo===========+++++++++",decodedString)
            //window.localStorage.setItem("menus",decodedString)
            //const md5Hash = md5(decodedString+'menus_list');
            //window.localStorage.setItem("md5Hash",md5Hash)     
            departmentdata.value=JSON.parse(decodedString)
            //console.log("departmentinfo=======---------------------====+++++++++",departmentdata)
            // 存储菜单数据到 localStorage
            // const decodedString = window.localStorage.getItem('menus');
            // 返回解析后的菜单数据
            // return JSON.parse(decodedString);
        }
      })
  }
// 清空userForm表单数据
const clearUserForm = () => {
  Object.keys(userForm).forEach(key => {
    userForm[key] = "";
  });
};

// 定义接收事件的函数
const handleSubmit = async (formData) => {
  try {
    // 在父组件中执行相应的逻辑，例如提交数据到后端
    console.log('接收到的表单数据：', formData);
    // 创建一个新对象，排除 "password" 属性
    const { checkpass, ...newformData } = formData;
    console.log("newformData=============",newformData)
    newformData["department_name"]=newformData["department_name"].toString();
    const response = await addUserHandler(newformData)
    if (response.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
    dialogFormVisible.value=false
    console.log("userForm=====+++++++",userForm)
    clearUserForm()
    console.log("userForm=====+++++++",userForm)
    // 可以在这里做API请求等操作
  } catch(error){
    console.log(error)
  }
};
onMounted(()=>{
  getUserInfo()
  getDepartmentData()
})



</script>
<style scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.search-input {
  margin-left: 10px;
  width: 300px;
}
.table-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;

}

</style>
